
// Day16手写：
// 1.手写算法：https://leetcode-cn.com/problems/find-bottom-left-tree-value/

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function (root) {
    let max = 0, res = null;
    function find(root, cur) {
        if (!root.left && !root.right) {
            if (cur > max) {
                max = Math.max(max, cur)
                res = root.val;
            }
        }
        if (root.left) find(root.left, cur + 1)
        if (root.right) find(root.right, cur + 1)
    }
    find(root, 1)
    return res;
};


var findBottomLeftValue = function (root) {
    //考虑层序遍历 记录最后一行的第一个节点
    let queue = [];
    if (root === null) {
        return null;
    }
    queue.push(root);
    let resNode;
    while (queue.length) {
        let length = queue.length;
        for (let i = 0; i < length; i++) {
            let node = queue.shift();
            if (i === 0) {
                resNode = node.val;
            }
            node.left && queue.push(node.left);
            node.right && queue.push(node.right);
        }
    }
    return resNode;
};

// 2.手写题

// 实现一个LazyMan，可以按照以下方式调用:
// LazyMan('Hank')输出:
// Hi! This is Hank!

// LazyMan('Hank').sleep(10).eat('dinner')输出
// Hi! This is Hank!
//     //等待10秒..
//     Wake up after 10
//     Eat dinner~

//     LazyMan('Hank').eat('dinner').eat('supper')输出
//     Hi This is Hank!
//     Eat dinner~
//     Eat supper~
//         LazyMan('Hank').eat('supper').sleepFirst(5)输出
//     //等待5秒
//     Wake up after 5
//     Hi This is Hank!
//     Eat supper

function LazyMan(name) {
    function fn(name) {
        console.log('Hi! This is ', name)
        this.name = name;
        this.eventQueue = []
        return this
    }
    fn.prototype.sleep = function (s) {
        const f = () => {
            setTimeout(() => {
                console.log('Wake up after ', s);
            }, s * 1000)
        }
        this.queue.push(f)
        return this;
    }

    fn.prototype.eat = function (food) {
        const f = () => {
            setTimeout(() => {
                console.log(`Eat ${food}~`)
            }, 0);
        }
        this.queue.push(f)
        return this;
    }

    fn.prototype.sleepFirst = function (s) {
        const f = () => {
            setTimeout(() => {
                console.log('Wake up after ', s);
            }, s * 1000)
        }
        this.queue.unshift(f)
        return this
    }
    return new fn(name)
}


LazyMan('Hank').sleep(10)